package com.scfire.checkData

import java.util.List;

import net.sf.json.JSONObject

import com.alipay.api.AlipayClient
import com.alipay.api.DefaultAlipayClient
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse
import com.scfire.alipay.AlipayConfig
import com.scfire.project.Donate
import com.scfire.util.CsvUtil;
import com.scfire.util.DateUtil
import com.scfire.util.FileUtil
import com.scfire.util.MailUtil
import com.scfire.util.ZipUtil
import com.scfire.weixin.MD5Sign
import com.scfire.weixin.WeiXinConstants
import com.scfire.weixin.WeiXinUtil

class DataService {
	def payService
	def downLoad(String date) throws Exception {
		SortedMap<Object,Object> parameters =new TreeMap<Object,Object>();
		String nonce_str = WeiXinUtil.getRandomString(32)
		parameters.put("appid",WeiXinConstants.appid);
		parameters.put("mch_id",WeiXinConstants.mch_id);
//     parameters.put("device_info", "");//微信支付分配的终端设备号，填写此字段，只下载该设备号 的对账单
		parameters.put("nonce_str",nonce_str);
		parameters.put("bill_date",date);//下载对账单的日期，格式：20140603，日期不可为当天。
		//bill_type:ALL返回当日所有订单信息,默认值SUCCESS返回当日成功支付的订单。REFUND，返回当日退款订单
		parameters.put("bill_type","SUCCESS");
		String sign = MD5Sign.createSign("UTF-8",parameters , WeiXinConstants.mch_key)
		parameters.put("sign", sign);
		String reuqestXml =WeiXinUtil.getRequestXml(parameters);
		String result=WeiXinUtil.httpsRequest(WeiXinConstants.DOWNLOAD_BILL_URL, "POST",reuqestXml);
		
		 if(result.startsWith("<xml>")){//查询日期为当天时，错误信息提示日期无效
			System.out.println(result);
			System.out.println("无订单");
			}else{
			String[] forCheck = result.trim().split("@@");
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<forCheck.size();i++){
				if(forCheck[i].startsWith("`")){
					String[] readLine = (forCheck[i].trim().replaceAll(",`","`")).split("`");
					System.out.println(readLine.toString());
					
					if(readLine.size()==19){
							//交易时间,公众账号ID,商户号,子商户号,设备号,微信订单号,商户订单号,用户标识,交易类型,交易状态,付款银行,货币种类,总金额,企业红包金额,微信退款单号,商户退款单号,退款金额,企业红包退款金额,退款类型,退款状态,商品名称,商户数据包,手续费,费率
							def donate = Donate.findByOut_trade_no(readLine[7].trim())
							println readLine[16]+"@@"
							String attach = readLine[16].replaceAll('\\\\','').replaceAll('" "','","')
							
							println attach+"@@@"
							def  attachJSON = JSONObject.fromObject(attach)
							def donate_fee = attachJSON.df as float
							if(donate!=null){
								System.out.println("------"+donate_fee);
												 
								if(donate.donate_fee==donate_fee){
									System.out.println("true")
								}else{
								sb.append("异常数据：").append(attachJSON);
								sb.append("\r\n");
								
								}
							}else{
							String projectId = attachJSON.p
							String memberId = attachJSON.m
							boolean checked
							if("true".equalsIgnoreCase(attachJSON.c)){
								checked = true
							}else{
								checked = false
							}
							def operate_fee = attachJSON.of as float
							def subprojectid = attachJSON.s
							def donateNoNew = attachJSON.dn
							String total_fee = readLine[13].trim();
							String result_code = "SUCCESS"
							String out_trade_no = readLine[7].trim();
							String openid = readLine[8].trim();
							String transaction_id =readLine[6].trim();
							if(donate!=null){
								println "memberId:"+donate.member+"--projectId:"+donate.project+"--donate_fee:"+donate.donate_fee+"--operate_fee:"+donate.operate_fee+"--subprojectid:"+donate?.subProject+"--total_fee:"+donate?.money+"--out_trade_no:"+donate.out_trade_no+"--openid:"+donate.openid+"--transaction_id:"+donate.transaction_id+"--checked:"+donate.operate_fee_status+"--attach:"+donate.attach+"--donateNoNew:"+donate.donateNoNew
							}
							
							println "memberId:"+memberId+"--projectId:"+projectId+"--donate_fee:"+donate_fee+"--operate_fee:"+operate_fee+"--subprojectid:"+subprojectid+"--total_fee:"+total_fee+"--out_trade_no:"+out_trade_no+"--openid:"+openid+"--transaction_id:"+transaction_id+"--checked:"+checked+"--attach:"+attach+"--donateNoNew:"+donateNoNew
							
							sb.append("丢失数据：").append(attachJSON);
							sb.append("\r\n");
							 boolean flag = payService.checkCallBack(memberId, projectId, donate_fee, operate_fee, subprojectid, total_fee, out_trade_no, openid, transaction_id, false, attach,donateNoNew,"微信支付",readLine[1])
							if(flag==false){
								sb.append("存储异常：").append(attachJSON);
								sb.append("\r\n");
							}
							//boolean flag = payService.weixinCallBack(memberId, projectId, donate_fee, operate_fee, subprojectid, total_fee, out_trade_no, openid, transaction_id, checked, attach,donateNoNew)
							}
					}
				}
			}
			if(sb!=null){
				MailUtil mailUtil = new MailUtil();
				println sb.toString();
				//mailUtil.sendEmal(sb.toString());
			}
		}
	}
	
	
	
	/**
	 * @param date
	 * @return
	 * ZAMX
	 * 2016年8月31日
	 */
	def downAliData(String date){
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",AlipayConfig.app_id,AlipayConfig.private_key,"json","GBK",AlipayConfig.public_key);
		AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
		request.setBizContent("{" +
		"    \"bill_type\":\"signcustomer\"," +
		"    \"bill_date\":\""+date+"\"" +
		"  }");
		AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
			String filePath = response.getBillDownloadUrl()
			//DateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd");
			boolean flag = FileUtil.fileCopy(filePath,WeiXinConstants.imgDir+AlipayConfig.partner+"0156"+DateUtil.getDate("yyyyMMdd",-1)+".zip");
			if(flag==true){
				println "true"+"0"
				boolean isZip = ZipUtil.unZip(WeiXinConstants.imgDir+AlipayConfig.partner+"0156"+DateUtil.getDate("yyyyMMdd",-1)+".zip", WeiXinConstants.imgDir)
				if(isZip==true){
					CsvUtil parser = new CsvUtil(WeiXinConstants.imgDir+AlipayConfig.partner+"0156_"+DateUtil.getDate("yyyyMMdd",-1)+"_账务明细.csv");
					List<String[]> list = parser.parse();
					if(list!=null){
						for(int i=0;i<list.size();i++){
							String[] temp = list.get(i);
							
							if(temp.size()>2){
								if(temp[3].trim()=="火堆公益"){
									
									String out_trade_no = temp[2].trim();
									println out_trade_no
									def donate = Donate.findByOut_trade_no(out_trade_no)
									if(donate==null){
									}
								}
							}
							
						}
						
						
					}
				}
				
				
				
				
				
				
				
				
				
				
				
			}
			
			
			
			
		System.out.println("调用成功");
		
		
		} else {
		System.out.println("调用失败");
		}
	}
	
	

	
	
}
